﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

namespace d39
{
    public class GridChangeEventArgs : EventArgs
    {
        public bool PlayersOrMovesChanged { get; set; }
        public bool WallTerrainChanged { get; set; }
    }
    public abstract class GridPage : Page
    {
        public Grid CurrentGrid
        {
            get
            {
                if (ViewState["CurrentGrid"] == null) ViewState["CurrentGrid"] = Grid.FromQueryString(Request.QueryString);
                return (Grid)ViewState["CurrentGrid"];
            }
        }

        public abstract string SubTitle { get; }

        public virtual IEnumerable<GridCommand> Commands { get { yield break; } }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.GridUpdate += (sender, args) => UpdateFromGrid(args.PlayersOrMovesChanged, args.WallTerrainChanged);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!IsPostBack) GridChanged(true, true);
        }

        protected virtual void UpdateFromGrid(bool playersOrMovesChanged, bool wallTerrainChanged)
        {
        }

        public void GridChanged(bool playersOrMovesChanged, bool wallTerrainChanged)
        {
            if (wallTerrainChanged)
            {
                if (CurrentGrid.Name != null)
                {
                    Title = CurrentGrid.Name + " - " + SubTitle + " - d39 grid";
                }
                else
                {
                    Title = SubTitle + " - d39 grid";
                }
            }
            var gridUpdate = GridUpdate;
            if (gridUpdate != null)
            {
                gridUpdate(this, new GridChangeEventArgs()
                    {
                        PlayersOrMovesChanged = playersOrMovesChanged,
                        WallTerrainChanged = wallTerrainChanged,
                    });
            }
        }
        public event EventHandler<GridChangeEventArgs> GridUpdate;
    }
}